package com.appspot.zarm.gomoku.action;

import com.appspot.zarm.controller.GameAction;
import com.appspot.zarm.controller.GameActionResult;
import com.appspot.zarm.controller.user.User;
import com.appspot.zarm.game.Game;
import com.appspot.zarm.game.GamesStorage;
import com.appspot.zarm.game.Player;
import com.appspot.zarm.gomoku.Coord;
import com.appspot.zarm.gomoku.GomokuGame;
import com.appspot.zarm.gomoku.GomokuGameFacade;
import com.appspot.zarm.gomoku.transfer.GameExternalizer;
import com.appspot.zarm.gomoku.transfer.GomokuJsonTransferer;
import com.appspot.zarm.transfer.GameState;
import com.appspot.zarm.transfer.Transferer;

public class GomokuAction extends GameAction {

	public static final String TURN_ACTION = "turn";
	
	public GomokuAction(GamesStorage gamesStorage) {
		super(gamesStorage);
	}

	@Override
	protected GameActionResult processActions(GameActionResult gameActionResult, User user, String action, Object data) {
		if (action.equals(TURN_ACTION)) {
			
			Player player = getGamesStorage().getPlayer(user);
			GomokuGame game = (GomokuGame) getGamesStorage().getGame(player);
			GomokuGameFacade gomokuGameFacade = new GomokuGameFacade(game, player);
			Coord position = (Coord)data;
			
			if (game.getState() == GameState.GAME_CONTINUING) {
				
				gomokuGameFacade.doTurn(position);
				if (game.getState() == GameState.PLAYER_WINS) {
					// todo
				} else if (game.getState() == GameState.COMPUTER_WINS) {
					// todo
				}
			}
			GameActionResult gar = new GameActionResult();
			gar.setData((GameExternalizer) game);
			return gar;
		} else {
			return gameActionResult;
		}
	}


	@Override
	public Game newGame(Player player) {
		return new GomokuGame(player);
	}

	@Override
	public Transferer newTransferer(String transfererType) {
		if ( transfererType.equals("json") ){
			return new GomokuJsonTransferer();
		} else {
			throw new IllegalArgumentException("wrong transferer type " + transfererType);
		}
	}

	
}
